﻿/*************************************************************************************
 *
 * 文 件 名： Worker
 * 描    述： 从模板新增
 * 
 * 版    本： V1.0
 * 创 建 者： YSW
 * 创建时间： 2022-08-24 8:54:29
 * ======================================
 * 历史更新记录
 * 版本：V          修改时间：         修改人：
 * 修改内容：
 * ======================================
*************************************************************************************/

using CommonModel.Util;
using GXRTBTC.PublicClassLibrary.Util;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Infrastructure;
using System.Text;

namespace GXRTBTC.WebReceiveService.Controllers
{
    [EnableCors("any")]
    [Route("[controller]")]
    //IgnoreApi = false/true 窗口是否显示到swaggerUI
    [ApiExplorerSettings(IgnoreApi = false)]
    [ApiController]
    public class WebReceiveController : ControllerBase
    {
        public Worker worker;
        public WebReceiveController(Worker worker)
        {
            //支持gb2312编码
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            this.worker = worker;
        }

        /// <summary>
        /// 在这里做一个访问统计记录日志等
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public override OkObjectResult Ok([ActionResultObjectValue] object? value)
        {
            worker.SetStatistics(HttpContext);
            return base.Ok(value);
        }

        /// <summary>
        /// 状态监控接口
        /// </summary>
        /// <returns></returns>
        [HttpGet("Status")]
        public OkObjectResult GetStatus()
        {
            return Ok(worker.GetStatus());
        }

        /// <summary>
        /// 接收提交json数据
        /// 数字信号源数据
        /// 由玉龙发送
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost]
        public bool GetDataFrom([FromBody] object data)
        {
            try
            {
                if (data != null && !"".Equals(data.ToString()) && ValidJson.IsJson(data.ToString()))
                {
                    //return worker.GetDataFromJson(data.ToString(), HttpContext);
                    return worker.DataFromJsonToCache(data.ToString(), HttpContext);
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        /// <summary>
        /// 新协议接口
        /// json接口
        /// 20250411
        /// </summary>
        /// <param name="apiver">API协议版本</param>
        /// <param name="level">级别 SYSTEM(系统级) DEVICE(设备级)</param>
        /// <param name="positionid">位置编号，xx_xxx_xxx，（对应模型中的位置编号）</param>
        /// <param name="sn">系统/设备序列号，要求唯一性，不可更改</param>
        /// <param name="data"></param>
        /// <returns></returns>
        //[HttpPost("data")]
        ////public OkObjectResult GetDataJson(string? apiver, string? level, string? positionid, string? sn, [FromBody] object data)
        //public OkObjectResult GetDataJson([FromBody] object data)
        //{
        //    return Ok(worker.DealingJsonData(HttpContext, data.ToString()).ContentRes);
        //}

        /// <summary>
        /// 新远场数据接收
        /// 玉龙负责对接科江
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("datayc")]
        [RequestFormLimits(MultipartBodyLengthLimit = int.MaxValue)]
        [RequestSizeLimit(int.MaxValue)]
        [DisableRequestSizeLimit]
        [Consumes("application/xml")]   //入参是xml 
        public OkObjectResult GetDataYcNew()
        {
            try
            {
                var len = Convert.ToInt32(HttpContext.Request.ContentLength);
                string data = "";

                //byte[] byt = new byte[len];
                //var ri = HttpContext.Request.BodyReader.AsStream().Read(byt, 0, len);
                //string data = Encoding.UTF8.GetString(byt, 0, len);
                //string data = Encoding.GetEncoding(TransForm.encode).GetString(byt, 0, len);

                //循坏才能读取所有数据
                //int cnt = 0;
                //while (true && len > 0)
                //{
                //    ReadResult readResult = HttpContext.Request.BodyReader.ReadAsync().Result;
                //    var buffer = readResult.Buffer;
                //    cnt += Convert.ToInt32(buffer.Length);
                //    data += Encoding.UTF8.GetString(readResult.Buffer);
                //    HttpContext.Request.BodyReader.AdvanceTo(readResult.Buffer.GetPosition(buffer.Length));
                //    if (cnt >= len || readResult.IsCompleted || readResult.IsCanceled)
                //    {
                //        break;
                //    }
                //}

                //循坏才能读取所有数据
                var stream = HttpContext.Request.BodyReader.AsStream();
                byte[] buffer = new byte[len];
                int bytesRead = 0;
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
#if DEBUG
                    data += Encoding.UTF8.GetString(buffer, 0, bytesRead);
#else
                    data += Encoding.GetEncoding(TransForm.encode).GetString(buffer, 0, bytesRead);
#endif
                }

                if (len > 0)
                {
                    //return Ok(worker.GetDataYC(data ?? "", HttpContext));
                    return Ok(worker.DataFromXmlToCache(data ?? "", HttpContext));
                }
                else
                {
                    return Ok(new Dictionary<string, Object>() { { "return_code", -1 }, { "return_msg", "data error" }, { "node_name", worker.nodeName }, { "time", -1 }, { "current", TransForm.GetFormatDatetime() } });
                }
            }
            catch (Exception e)
            {
                return Ok(new Dictionary<string, Object>() { { "return_code", -1 }, { "return_msg", e.Message }, { "node_name", worker.nodeName }, { "time", -1 }, { "current", TransForm.GetFormatDatetime() } });
            }
        }

        /// <summary>
        /// xml测试接口
        /// </summary>
        /// <param name="data"></param>
        /// <returns></returns>
        [HttpPost("xmltest")]
        [RequestFormLimits(MultipartBodyLengthLimit = int.MaxValue)]
        [RequestSizeLimit(int.MaxValue)]
        [DisableRequestSizeLimit]
        [Consumes("application/xml")]
        public OkObjectResult GetDataYcNewTest()
        {
            try
            {
                var len = Convert.ToInt32(HttpContext.Request.ContentLength);
                string data = "";

                //循坏才能读取所有数据
                var stream = HttpContext.Request.BodyReader.AsStream();
                byte[] buffer = new byte[len];
                int bytesRead = 0;
                while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
                {
#if DEBUG
                    data += Encoding.UTF8.GetString(buffer, 0, bytesRead);
#else
                    data += Encoding.GetEncoding(TransForm.encode).GetString(buffer, 0, bytesRead);
#endif
                }

                if (len > 0)
                {
                    return Ok(new Dictionary<string, Object>() { { "return_code", 0}, { "return_msg", "success" }, { "node_name", worker.nodeName }, { "time", 0 }, { "current", TransForm.GetFormatDatetime() } });
                }
                else
                {
                    return Ok(new Dictionary<string, Object>() { { "return_code", -1 }, { "return_msg", "data error" }, { "node_name", worker.nodeName }, { "time", -1 }, { "current", TransForm.GetFormatDatetime() } });
                }
            }
            catch (Exception e)
            {
                return Ok(new Dictionary<string, Object>() { { "return_code", -1 }, { "return_msg", e.Message }, { "node_name", worker.nodeName }, { "time", -1 }, { "current", TransForm.GetFormatDatetime() } });
            }
        }

        /// <summary>
        /// 海康威视人脸识别回调
        /// </summary>
        /// <param name="bodyParam"></param>
        /// <returns></returns>
        [HttpPost("HKFaceCallBack")]
        public OkObjectResult HKFaceCallBack([FromBody] object bodyParam)
        {
            return Ok(worker.HKFaceCallBack(bodyParam == null ? null : bodyParam.ToString(), HttpContext).Result);
        }

        [HttpGet("ServiceTime")]
        public OkObjectResult GetServiceTime()
        {
            return Ok(string.Format("{0:yyyy-MM-dd HH:mm:ss.ffffff}", DateTime.Now));
        }

        /// <summary>
        /// 这是get方法
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public string Get()
        {
            return "连接正常";
        }
    }
}
